<template>
  <div class="trash-container">
    <!-- 可回收垃圾 -->
    <div class="trash-card">
      <el-card class="box-card" style="--header-bg: #409eff">
        <template #header>
          <div class="card-header">
            <span>♻️ 可回收垃圾</span>
            <el-date-picker
              v-model="recyclableDateRange"
              type="date"
              placeholder="选择日期"
              @change="filterRecyclableData"
              size="small"
              style="width: 240px"
            />
          </div>
        </template>
        <el-table
          :data="
            recyclableData.slice(
              (recyclablePage.currentPage - 1) * recyclablePage.pageSize,
              recyclablePage.currentPage * recyclablePage.pageSize
            )
          "
          style="width: 100%"
          height="700"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="name" label="物品名称" width="180" />
          <el-table-column label="数量">
            <template #default="{ row }">
              <el-tag type="info">{{ row.quantity }}件</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="重量(kg)" />
          <el-table-column prop="date" label="收录日期" width="180" />
          <el-table-column prop="time" label="收录时间" width="180" />
        </el-table>
        <el-pagination
          v-model:current-page="recyclablePage.currentPage"
          v-model:page-size="recyclablePage.pageSize"
          :page-sizes="[5, 10, 15]"
          layout="total, sizes, prev, pager, next"
          :total="recyclableData.length"
          class="pagination"
        />
      </el-card>
    </div>

    <!-- 其他三个垃圾桶（厨余/有害/其他）结构类似，修改数据绑定和样式即可 -->
    <!-- 厨余垃圾 -->
    <div class="trash-card">
      <el-card class="box-card" style="--header-bg: #67c23a">
        <template #header>
          <div class="card-header">
            <span>🍂 厨余垃圾</span>
            <el-date-picker
              v-model="kitchenDateRange"
              type="date"
              placeholder="选择日期"
              @change="filterKitchenData"
              size="small"
              style="width: 240px"
            />
          </div>
        </template>
        <el-table
          :data="
            kitchenData.slice(
              (kitchenPage.currentPage - 1) * kitchenPage.pageSize,
              kitchenPage.currentPage * kitchenPage.pageSize
            )
          "
          style="width: 100%"
          height="700"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="name" label="物品名称" width="180" />
          <el-table-column label="数量">
            <template #default="{ row }">
              <el-tag type="success">{{ row.quantity }}件</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="重量(kg)" />
          <el-table-column prop="time" label="收录时间" width="180" />
        </el-table>
        <el-pagination
          v-model:current-page="kitchenPage.currentPage"
          v-model:page-size="kitchenPage.pageSize"
          :page-sizes="[5, 10, 15]"
          layout="total, sizes, prev, pager, next"
          :total="kitchenData.length"
          class="pagination"
        />
      </el-card>
    </div>

    <!-- 有害垃圾 -->
    <div class="trash-card">
      <el-card class="box-card" style="--header-bg: #f56c6c">
        <template #header>
          <div class="card-header">
            <span>⚠️ 有害垃圾</span>
            <el-date-picker
              v-model="hazardousDateRange"
              type="date"
              placeholder="选择日期"
              @change="filterHazardousData"
              size="small"
              style="width: 240px"
            />
          </div>
        </template>
        <el-table
          :data="
            hazardousData.slice(
              (hazardousPage.currentPage - 1) * hazardousPage.pageSize,
              hazardousPage.currentPage * hazardousPage.pageSize
            )
          "
          style="width: 100%"
          height="700"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="name" label="物品名称" width="180" />
          <el-table-column label="数量">
            <template #default="{ row }">
              <el-tag type="danger">{{ row.quantity }}件</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="重量(kg)" />
          <el-table-column prop="time" label="收录时间" width="180" />
        </el-table>
        <el-pagination
          v-model:current-page="hazardousPage.currentPage"
          v-model:page-size="hazardousPage.pageSize"
          :page-sizes="[5, 10, 15]"
          layout="total, sizes, prev, pager, next"
          :total="hazardousData.length"
          class="pagination"
        />
      </el-card>
    </div>

    <!-- 其他垃圾 -->
    <div class="trash-card">
      <el-card class="box-card" style="--header-bg: #909399">
        <template #header>
          <div class="card-header">
            <span>🗑️ 其他垃圾</span>
            <el-date-picker
              v-model="otherDateRange"
              type="date"
              placeholder="选择日期"
              @change="filterOtherData"
              size="small"
              style="width: 240px"
            />
          </div>
        </template>
        <el-table
          :data="
            otherData.slice(
              (otherPage.currentPage - 1) * otherPage.pageSize,
              otherPage.currentPage * otherPage.pageSize
            )
          "
          style="width: 100%"
          height="700"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="name" label="物品名称" width="180" />
          <el-table-column label="数量">
            <template #default="{ row }">
              <el-tag>{{ row.quantity }}件</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="重量(kg)" />
          <el-table-column prop="time" label="收录时间" width="180" />
        </el-table>
        <el-pagination
          v-model:current-page="otherPage.currentPage"
          v-model:page-size="otherPage.pageSize"
          :page-sizes="[5, 10, 15]"
          layout="total, sizes, prev, pager, next"
          :total="otherData.length"
          class="pagination"
        />
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { selectLaunchByMaterial } from "@/api/system/screen.js";
import { listTrash } from "@/api/system/trash.js";
const route = useRoute();
// 从路由参数中获取物料类型参数
let { query } = route;
// 日期范围
const recyclableDateRange = ref(null);
const kitchenDateRange = ref(null);
const hazardousDateRange = ref(null);
const otherDateRange = ref(null);

// 原始数据
const originalRecyclableData = ref([]);
const originalKitchenData = ref([]);
const originalHazardousData = ref([]);
const originalOtherData = ref([]);

// 筛选后的数据
const recyclableData = reactive([]);
const kitchenData = reactive([]);
const hazardousData = reactive([]);
const otherData = reactive([]);

// 分页配置
const paginationConfig = () => ({
  currentPage: 1,
  pageSize: 5,
});

const recyclablePage = reactive(paginationConfig());
const kitchenPage = reactive(paginationConfig());
const hazardousPage = reactive(paginationConfig());
const otherPage = reactive(paginationConfig());

const pointId = ref(null);
const trashData = ref([]);
onMounted(() => {
  console.log("query", query);
  pointId.value = query.pointId;

  Promise.all([getTrashData()]).then(async (res) => {
    // 初始化数据
    originalRecyclableData.value = await generateData("可回收");
    originalKitchenData.value = await generateData("厨余");
    originalHazardousData.value = await generateData("有害");
    originalOtherData.value = await generateData("其他");

    // 复制初始数据到显示数据
    Object.assign(recyclableData, originalRecyclableData.value);
    Object.assign(kitchenData, originalKitchenData.value);
    Object.assign(hazardousData, originalHazardousData.value);
    Object.assign(otherData, originalOtherData.value);
  });
});
// 根据点位获取该点位垃圾桶数据
const getTrashData = async () => {
  try {
    let result = await listTrash({
      pointId: pointId.value,
    });
    if (result.code === 200) {
      trashData.value = result.rows;
    }
  } catch (error) {}
};

// 获取垃圾数据
const generateData = async (type) => {
  let trashId = null;
  trashData.value.forEach(async (item) => {
    if (item.trashType === type) {
      trashId = item.id;
    }
  });
  if (trashId) {
    try {
      let result = await selectLaunchByMaterial({
        pointId: pointId.value,
        trashId: trashId,
      });
      if (result.code === 200) {
        const data = result.data.map((item) => {
          return {
            name: item.MATERIALNAME,
            quantity: item.SUMCAPACITY,
            weight: item.SUMWEIGHT,
            time: item.launchtime,
            date: item.launchDate,
          };
        });
        console.log("data", data);
        return data;
      }
    } catch (error) {}
  } else {
    return [];
  }
};

// 获取点位数据
const getPointData = async () => {
  try {
    let result = await listPoint({
      pointName: pointName.value,
    });
    if (result.code === 200) {
      pointData.value = result.rows;
    }
  } catch (error) {}

  // return Array.from({ length: 18 }, (_, i) => ({
  //   name: `${type}物品${i + 1}`,
  //   quantity: Math.floor(Math.random() * 5) + 1,
  //   weight: (Math.random() * 0.1).toFixed(3),
  //   time: `2023-09-${String(15 + Math.floor(i / 6)).padStart(2, "0")} ${String(
  //     8 + (i % 6)
  //   ).padStart(2, "0")}:30:00`,
  // }));
};

// 日期筛选函数

const filterByDateRange = (data, date) => {
  if (!date) return data;

  return data.filter((item) => {
    const itemDate = new Date(item.date).toDateString();
    const selectedDate = new Date(date).toDateString();
    
    return itemDate === selectedDate;
  });
  
};
// const filterByDateRange = (data, date) => {
//   if (!date) return data;

//   return data.filter((item) => {
//     const itemDate = new Date(item.date).toDateString();
//     const selectedDate = new Date(date).toDateString();
    
//     return itemDate === selectedDate;
//   });
  
// };

// 各类垃圾的筛选函数
// const filterRecyclableData = () => {
//   Object.assign(
//     recyclableData,
//     filterByDateRange(originalRecyclableData.value, recyclableDateRange.value)
//   );
//   console.log("recyclableData",  filterByDateRange(originalRecyclableData.value, recyclableDateRange.value));
//   recyclablePage.currentPage = 1;
// };
const filterRecyclableData = () => {
  const filtered = filterByDateRange(originalRecyclableData.value, recyclableDateRange.value);
  // 清空数组后重新填充（保持响应性）
  recyclableData.splice(0, recyclableData.length, ...filtered);
  console.log("recyclableData", filtered);
  recyclablePage.currentPage = 1;
};

const filterKitchenData = () => {
  const filtered = filterByDateRange(originalRecyclableData.value, kitchenDateRange.value);
  // 清空数组后重新填充（保持响应性）
  kitchenData.splice(0, kitchenData.length, ...filtered);
  console.log("recyclableData", filtered);
  recyclablePage.currentPage = 1;
};
const filterHazardousData = () => {
  const filtered = filterByDateRange(originalRecyclableData.value, hazardousDateRange.value);
  // 清空数组后重新填充（保持响应性）
  hazardousData.splice(0, hazardousData.length, ...filtered);
  console.log("recyclableData", filtered);
  recyclablePage.currentPage = 1;
};
const filterOtherData = () => {
  const filtered = filterByDateRange(originalRecyclableData.value, otherDateRange.value);
  // 清空数组后重新填充（保持响应性）
  otherData.splice(0, otherData.length, ...filtered);
  console.log("recyclableData", filtered);
  recyclablePage.currentPage = 1;
};
// const filterKitchenData = () => {
//   Object.assign(
//     kitchenData,
//     filterByDateRange(originalKitchenData.value, kitchenDateRange.value)
//   );
//   kitchenPage.currentPage = 1;
// };

// const filterHazardousData = () => {
//   Object.assign(
//     hazardousData,
//     filterByDateRange(originalHazardousData.value, hazardousDateRange.value)
//   );
//   hazardousPage.currentPage = 1;
// };

// const filterOtherData = () => {
//   Object.assign(
//     otherData,
//     filterByDateRange(originalOtherData.value, otherDateRange.value)
//   );
//   otherPage.currentPage = 1;
// };

// 表格行样式
const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 1 ? "even-row" : "";
};
</script>

<style scoped lang="scss">
.trash-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: 24px;
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 48px);
}

.trash-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease;

  &:hover {
    transform: translateY(-4px);
  }

  .box-card {
    border: none;

    :deep(.el-card__header) {
      background: var(--header-bg);
      border-radius: 12px 12px 0 0;
      padding: 16px;

      .card-header {
        color: white;
        font-weight: 600;
        font-size: 18px;
        display: flex;
        align-items: center;
        gap: 12px;

        :deep(.el-date-editor) {
          margin-left: auto;
          .el-range-separator,
          .el-range-input,
          .el-range__icon,
          .el-range__close-icon {
            color: white;
          }
        }
      }
    }

    :deep(.el-card__body) {
      padding: 16px;
    }
  }
}

.pagination {
  padding: 16px;
  background: white;
  border-radius: 0 0 12px 12px;
  display: flex;
  justify-content: center;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;

  .even-row {
    background-color: #fafafa;
  }

  .el-table__row:hover {
    background-color: #f5f7fa !important;
  }

  th.el-table__cell {
    background-color: #f8f9fa;
    font-weight: 600;
  }

  td.el-table__cell {
    padding: 12px 0;
  }
}
</style>
